<template>
  <view class="cart-container">
    <!-- 收货地址区域 -->
    <my-address></my-address>

    <!-- 商品列表区域 -->
    <uni-swipe-action>
      <block v-for="(item, i) in cart" :key="i">
        <uni-swipe-action-item :options="options" @click="onClose(item)">
          <my-goods :goods="item" :showRadio="true" :showNoBox="true" @checkchange="goodsCheckChanged" @countchange="goodsCountChanged"></my-goods>
        </uni-swipe-action-item>
      </block>
    </uni-swipe-action>

    <!-- 结算区域 -->
    <view class="settlement-box">
      <view class="left">
        <radio :checked="isAllChecked" color="#C00000" @click="allCheckChanged" />
        <text>全选</text>
      </view>
      <view class="middle">
        <text>合计：</text>
        <text class="total-price">￥{{amount}}</text>
      </view>
      <view class="right" @click="btnSettlement">
        结算({{checkedGoodsTotal}})
      </view>
    </view>
  </view>
</template>

<script>
  import mix from '@/mixins/tabbar-badge.js'
  import { mapState, mapMutations, mapGetters } from 'vuex'

  export default {
    mixins: [mix],
    data() {
      return {
        options: [{
          text: '删除',
          style: {
            backgroundColor: '#dd524d'
          }
        }]
      }
    },
    methods: {
      ...mapMutations(['updateGoodsCount', 'updateGoodsChecked', 'updateAllChecked', 'removeGoods']),
      // 商品数量改变的事件处理函数
      goodsCountChanged(e) {
        const goods = this.cart.find(x => x.goods_id == e.goods_id)
        // 如果商品数量没变化或不合法，则不执行更新的操作
        if (goods.goods_count === e.value || !e.value) return
        this.updateGoodsCount({ goods_id: e.goods_id, count: e.value })
      },
      // 商品的选中状态发生了变化
      goodsCheckChanged(goods) {
        this.updateGoodsChecked({
          goods_id: goods.goods_id,
          is_checked: !goods.is_checked
        })
      },
      // 点击了全选的 radio
      allCheckChanged() {
        this.updateAllChecked(!this.isAllChecked)
      },
      // 点击了删除按钮
      onClose(goods) {
        this.removeGoods(goods.goods_id)
      },
      // 点击了结算按钮
      btnSettlement() {
        const address = JSON.parse(uni.getStorageSync('address') || '{}')
        // 判断收货地址是否为空
        if (!address.telNumber) {
          return uni.$showError('请选择收货地址！')
        }
        // 判断商品数量是否为空
        if (this.checkedGoodsTotal === 0) {
          return uni.$showError('请选择要结算的商品！')
        }
        // 判断是否登录了
        if (!this.token) {
          let time = 3
          let timerId = setInterval(() => {
            if (time - 1 === 0) {
              uni.hideToast()
              clearInterval(timerId)
              // 3 秒之后自动跳转到登录页面
              uni.switchTab({
                url: '/pages/my/my',
                success() {
                  // 跳转完成之后，传递参数
                  uni.$emit('redirect', {
                    from: '/pages/cart/cart',
                    openType: 'switchTab'
                  })
                }
              })
              return
            }
            time -= 1

            uni.showToast({
              icon: 'none',
              title: '请登录后再结算！' + time + '秒后自动跳转到登录页',
              mask: true
            })
          }, 1000)
          uni.showToast({
            icon: 'none',
            title: '请登录后再结算！' + time + '秒后自动跳转到登录页',
            mask: true
          })
          return
        }
        // 可以进行支付了
        this.payOrder(address)
      },
      // 支付订单金额
      async payOrder(address) {
        // 1. 创建订单
        const query1 = {
          // 订单金额
          order_price: 0.01,
          // 收货地址
          consignee_addr: address.provinceName + address.cityName + address.countyName + address.detailInfo,
          // 订单中包含的商品信息
          goods: this.cart.filter(x => x.is_checked).map(x => {
            return { goods_id: x.goods_id, goods_number: x.goods_count, goods_price: x.goods_price }
          })
        }
        const { data: res1 } = await uni.$http.post('/api/public/v1/my/orders/create', query1).catch(err => err)
        if (res1.meta.status !== 200) return uni.$showError('创建订单失败！')
        // 获取到服务器响应的订单编号
        const order_number = res1.message.order_number

        // 2. 订单预支付
        const { data: res2 } = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', { order_number }).catch(err => err)
        if (res2.meta.status !== 200) return uni.$showError('预付订单生成失败！')
        // 获取订单支付相关的必要参数
        const payInfo = res2.message.pay

        // 3. 调用 uni.requestPayment() 发起支付
        await uni.requestPayment({
          ...payInfo,
          success: (res) => {
            console.log('success', res)
            // {errMsg: "requestPayment:ok"}
            if (res.errMsg === 'requestPayment:ok') {
              return uni.$showError('订单支付成功！')
            }
          },
          fail: (err) => {
            console.log('fail', err)
            // {errMsg: "requestPayment:fail cancel"}
            if (err.errMsg === 'requestPayment:fail cancel') {
              return uni.$showError('您取消了支付！')
            }
          },
          complete: () => {
            console.log('pay complete')
          }
        })
      }
    },
    computed: {
      ...mapState(['cart', 'userInfo', 'token']),
      ...mapGetters(['checkedGoodsTotal']),
      // 是否全选
      isAllChecked() {
        const checkedLength = this.cart.filter(x => x.is_checked).length
        return checkedLength === this.cart.length
      },
      // 勾选的商品总数量
      // checkedGoodsCount() {
      //   let count = 0
      //   this.cart.forEach(x => {
      //     if (x.is_checked) {
      //       count += x.goods_count
      //     }
      //   })
      //   return count
      // },
      // 勾选的商品总价
      amount() {
        let _amount = 0
        this.cart.forEach(x => {
          if (x.is_checked) {
            _amount += x.goods_count * x.goods_price
          }
        })
        return _amount
      }
    }
  }
</script>

<style lang="scss">
  .cart-container {
    padding-bottom: 49px;
  }

  .thumb-box {
    display: flex;
    align-items: center;

    image {
      width: 180rpx;
      height: 180rpx;
      margin-left: 5rpx;
    }
  }

  .desc-box {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .price {
      font-size: 16px;
      color: #C00000;
    }
  }

  my-goods {
    width: 100%;
  }

  .settlement-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    bottom: 0;
    background-color: #FFFFFF;
    border-top: 1px solid #efefef;
    padding-left: 5px;
    z-index: 999;
    position: fixed;
    width: 100%;

    .middle {
      .total-price {
        color: #C00000;
      }
    }

    .right {
      background-color: #C00000;
      height: 100%;
      color: #FFFFFF;
      padding: 0 20px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
</style>
